
package com.v1.video.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.R;
import com.v1.video.activity.SettingRecommendAppActivity;
import com.v1.video.domain.RecommendAppInfo;
import com.v1.video.option.util.DownloadAppUtil;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.widgets.MyDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 
 * update 李新立   2014/6/20
 *      增加app下载点击事件统计
 */
public class OptionRecommendAdapter extends BaseAdapter {
    private List<RecommendAppInfo> infos;

    private DisplayImageOptions options;

    private final String TAG = "OptionRecommendAdapter";
    private LayoutInflater mInflater;

    public List<RecommendAppInfo> getInfos() {
        return infos;
    }

    public void setInfos(List<RecommendAppInfo> infos) {
        this.infos = infos;
    }

    private Context context;
    
//    Handler outHandler;
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch(msg.what){
                case RecommendAppInfo.STATUS_GO_DOWN:
                    infos.get(msg.arg1).setStatus(msg.what);
                    break;
                case RecommendAppInfo.STATUS_DOWNNING:
//                    infos.get(msg.arg1).setStatus(msg.what);
                    infos.get(msg.arg1).progress = msg.arg2;
//                    if(infos.get(msg.arg1).progress < msg.arg2){
//                        infos.get(msg.arg1).progress = msg.arg2;
//                    }                    
//                    Logger.i(TAG, "进度回传了msg.arg1=="+msg.arg1);
//                    Logger.i(TAG, "进度回传了msg.arg2=="+msg.arg2);
//                    Logger.i(TAG, "回传后进度_infos.get(msg.arg1).progress="+infos.get(msg.arg1).progress);
//                    notifyDataSetChanged();
                    break;
                case RecommendAppInfo.STATUS_STOP:
                    infos.get(msg.arg1).setStatus(msg.what);
                    break;
                case RecommendAppInfo.STATUS_DOWNED:
                    infos.get(msg.arg1).setStatus(msg.what);
                    break;
            }
            notifyDataSetChanged();
//            updata(infos);
        }

    };

    public OptionRecommendAdapter(Context context) {
        this.context = context;
        options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.icon_live_default)
                .showImageForEmptyUri(R.drawable.icon_live_default).showImageOnFail(R.drawable.icon_live_default)
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY)
                .cacheInMemory(true).cacheOnDisc(true).resetViewBeforeLoading(true)
                .displayer(new RoundedBitmapDisplayer(15)).build();
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        DownloadAppUtil.outerHandler = handler;
    }

    public OptionRecommendAdapter(Context context, List<RecommendAppInfo> infos,Handler outHandler) {
        this.context = context;
        this.infos = infos;
//        this.outHandler = outHandler;
        options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.icon_live_default)
                .showImageForEmptyUri(R.drawable.icon_live_default).showImageOnFail(R.drawable.icon_live_default)
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY)
                .cacheInMemory(true).cacheOnDisc(true).resetViewBeforeLoading(true)
                .displayer(new RoundedBitmapDisplayer(15)).build();
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        DownloadAppUtil.outerHandler = handler;
    }

    public void updata(List<RecommendAppInfo> infos) {
        this.infos = infos;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView != null && convertView instanceof LinearLayout)
            holder = (ViewHolder) convertView.getTag();
        else {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_recommend_app, parent,false);
            holder.nickname = (TextView) convertView.findViewById(R.id.recomm_app_name);
            holder.progress = (ProgressBar)convertView.findViewById(R.id.pb_progress);
            holder.intro = (TextView) convertView.findViewById(R.id.recomm_app_title);
            holder.icon = (ImageView) convertView.findViewById(R.id.recomm_app_icon);
            holder.btnInstall = (Button) convertView.findViewById(R.id.recomm_btn_install);
//            holder.layoutInstallBack = (RelativeLayout)convertView.findViewById(R.id.recomm_btn_install_back);
            convertView.setTag(holder);
        }

        final int pos = position;
        final RecommendAppInfo info = infos.get(position);
        holder.nickname.setText(info.getAppName());
        holder.intro.setText(info.getAppTitle());
//        Logger.i(TAG, "getview_infos.get(pos).progress="+pos+"="+infos.get(position).progress);
        holder.progress.setProgress(info.progress);
        if(info.getImgUrl() != null){
            if(info.getImgUrl().equals("")){
                holder.icon.setImageResource(R.drawable.icon_live_default);
            }else{
                ImageLoader.getInstance().displayImage(/* Constant.SERVER_IP+ */info.getImgUrl(),
                        holder.icon, options, new SimpleImageLoadingListener() {
                            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                ImageView iv = (ImageView) view;
                                iv.setImageBitmap(loadedImage);
                            }
                        });
            }
        }else{
            holder.icon.setImageResource(R.drawable.icon_live_default);
        }
        
        holder.btnInstall.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Logger.i(TAG, "点击事件。。。。");
                if(info.status == RecommendAppInfo.STATUS_GO_DOWN){
//                    info.status = RecommendAppInfo.STATUS_DOWNNING;
//                    if(DownloadAppUtil.outerHandler == null){
//                        DownloadAppUtil.outerHandler = handler;
//                    }
//                    DownloadAppUtil.startDownThread(context, info, handler,pos);//去下载                    
////                    ApkDownLoadManager apkManager = new ApkDownLoadManager(context, fileName, fileUrl);
////                    apkManager.showDownloadDialog();
                    appDetailView(pos);
                    SettingRecommendAppActivity.isCanRefresh = false;
                }else if(info.status == RecommendAppInfo.STATUS_STOP){//暂停状态，点击继续
//                    if(DownloadAppUtil.outerHandler == null){
//                        DownloadAppUtil.outerHandler = handler;
//                    }
                    Logger.i(TAG, "暂停状态点击了-->");
                    if(!Helper.checkConnection(context)){
                        ToastAlone.showToast((Activity)context, context.getResources().getString(R.string.net_no), 1);
                        return;
                    }
                    SettingRecommendAppActivity.isCanRefresh = false;
                    info.status = RecommendAppInfo.STATUS_DOWNNING;
                    DownloadAppUtil.startDownThread(context, info, handler,pos);//下载继续
                    notifyDataSetChanged();
                }else if(info.status == RecommendAppInfo.STATUS_DOWNNING){//继续状态，点击暂停
//                    if(DownloadAppUtil.outerHandler == null){
//                        DownloadAppUtil.outerHandler = handler;
//                    }
                    Logger.i(TAG, "继续状态点击了-->");
                    info.status = RecommendAppInfo.STATUS_STOP;
                    //暂停
                    DownloadAppUtil.stopDownLoad(info);
                    SettingRecommendAppActivity.isCanRefresh = false;
                    notifyDataSetChanged();
                }else if(info.status == RecommendAppInfo.STATUS_DOWNED){//下载完成，去安装
//                    DownloadAppUtil.outerHandler = handler;
                	SettingRecommendAppActivity.isCanRefresh = true;
                    DownloadAppUtil.installApk(context, info.saveFilePath);
                }else{//打开
//                    Intent open = new Intent();
//                    String classMain = info.getClassMain();
                	SettingRecommendAppActivity.isCanRefresh = false;
//                    if(classMain.contains(".")){
//                        open.setComponent(new ComponentName(info.getPackageName(), info.getClassMain()));
//                    }else{
//                        open.setComponent(new ComponentName(info.getPackageName(), "."+classMain));
//                    }
////                    open.setComponent(new ComponentName(info.getPackageName(), "cn.v1.www.mingren.android.activity.SplashActivity"));
                    Intent open = context.getPackageManager().getLaunchIntentForPackage(info.getPackageName());
                    context.startActivity(open);
                }                
                
            }
        });      
//        if(isInstall(info.getPackageName())){
////            holder.btnInstall.setImageResource(R.drawable.btn_attentioned);
//            holder.btnInstall.setText("打开");
//        }else{
////            holder.btnInstall.setImageResource(R.drawable.add_focus);
//            holder.btnInstall.setText("下载");
//        }
        if(info.status == RecommendAppInfo.STATUS_GO_DOWN){
            holder.btnInstall.setText("下载");
        }else if(info.status == RecommendAppInfo.STATUS_STOP){
            holder.btnInstall.setText("继续");
            holder.intro.setVisibility(View.GONE);
            holder.progress.setVisibility(View.VISIBLE);
        }else if(info.status == RecommendAppInfo.STATUS_DOWNNING){
            holder.btnInstall.setText("暂停");
            holder.intro.setVisibility(View.GONE);
            holder.progress.setVisibility(View.VISIBLE);
        }else if(info.status == RecommendAppInfo.STATUS_DOWNED){
            holder.intro.setVisibility(View.VISIBLE);
            holder.progress.setVisibility(View.GONE);
            holder.btnInstall.setText("安装");
        }else{
            holder.btnInstall.setText("打开");
        }

        return convertView;
    }

//    GetDataTask task;

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Object getItem(int position) {
        return infos.get(position);
    }

    @Override
    public int getCount() {
        return infos.size();
    }

//    private boolean isInstall(String packageName) {
//        if (packageName == null) {
//            return false;
//        }
//        if (packageName.equals("")) {
//            return false;
//        }
//        try {
//            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
//                    PackageManager.GET_UNINSTALLED_PACKAGES);
//            return true;
//        } catch (NameNotFoundException e) {
//            return false;
//        }        
//    }
    
    static class ViewHolder {
        TextView intro;

        TextView nickname;

        Button btnInstall;
//        RelativeLayout layoutInstallBack;
        ProgressBar progress;
        
        ImageView icon;
    }
     
    private MyDialog dialogCommon;
    /** 应用介绍 */
    private void appDetailView(final int pos) {
        dialogCommon = new MyDialog(context, R.style.dialog_custom);
        final RecommendAppInfo info = infos.get(pos);
//        dialogCommon = new MyDialog(this, R.style.dialog_person_head);
        dialogCommon.setContentView(R.layout.dialog_app_recommend);
        dialogCommon.setCancelable(false);
        dialogCommon.setCanceledOnTouchOutside(false);
        
        ImageView icon = (ImageView)dialogCommon.findViewById(R.id.app_icon);
        TextView txtSure = (TextView)dialogCommon.findViewById(R.id.app_btn_sure);
        if(info.getImgUrl() != null){
            if(info.getImgUrl().equals("")){
                icon.setImageResource(R.drawable.ic_launcher);
            }else{
                ImageLoader.getInstance().displayImage(/* Constant.SERVER_IP+ */info.getImgUrl(),
                        icon, options, new SimpleImageLoadingListener() {
                            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                ImageView iv = (ImageView) view;
                                iv.setImageBitmap(loadedImage);
                            }
                        });
            }
        }else{
            icon.setImageResource(R.drawable.ic_launcher);
        }
        
        ((TextView)dialogCommon.findViewById(R.id.app_name)).setText(info.getAppName());
        ((TextView)dialogCommon.findViewById(R.id.app_title)).setText(info.getAppTitle());
        ((TextView)dialogCommon.findViewById(R.id.app_detail)).setText(info.getAppDetail());
        dialogCommon.findViewById(R.id.app_btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogCommon.dismiss();                
            }
        });
        txtSure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//                if(isCanOnclick){
//                    //正在下载中，就不去凑热闹了
//                    return;
//                }
                dialogCommon.dismiss();
                if(!Helper.checkConnection(context)){
                    ToastAlone.showToast((Activity)context, context.getResources().getString(R.string.net_no), 1);
                    return;
                }
//                info.status = RecommendAppInfo.STATUS_STOP;
                info.status = RecommendAppInfo.STATUS_DOWNNING;
//                DownloadAppUtil.outerHandler = handler;
                DownloadAppUtil.startDownThread(context, info, handler,pos);
                notifyDataSetChanged();
                //友盟统计
                Map<String, String> map_ekv = new HashMap<String, String>();
                map_ekv.put("appName", info.getAppName());
                MobclickAgent.onEvent(context, "recommendApp_id",map_ekv);
            }
        });
        dialogCommon.show();
    }
    
    
//    /**
//     * 包安装观察器
//     */
//    class PackageInstallObserver extends IPackageInstallObserver.Stub {
//        /**
//         * 安装完成后调用此方法
//         *@param packageName 被安装的包名
//         *@param returnCode 安装完后的返回结果
//         */
//        public void packageInstalled(String packageName, int returnCode) {
//            Message msg = mHandler.obtainMessage(INSTALL_COMPLETE);
//            msg.arg1 = returnCode;
//            mHandler.sendMessage(msg);
//        }
//    }

}
